<template>
  <div>
    <!-- 基本信息 -->
    <div class="font-size-18 font-weight-700 margin-bottom-15">基本信息</div>
    <form-common v-if="baseInfoFiledList.length > 0" class="padding-right-20" :filed-list="baseInfoFiledList" ref="form" @selectChange="selectChange"></form-common>
    <!-- 对方信息 -->
    <div class="align-center margin-bottom-15">
      <span class="padding-right-20 font-size-18 font-weight-700">对方信息</span>
      <el-button v-if="!contractInfo.contractStatus" type="text" @click="addOtherItem">添加</el-button>
    </div>
    <template v-if="otherList.length > 0">
      <div class="full-box" :class="formIndex < otherList.length - 1 ? 'border-bottom-F2F2F2 margin-bottom-20' : ''" v-for="(formItem, formIndex) in otherList" :key="formItem.id">
        <form-common class="padding-right-20" :filed-list="formItem.listName" :ref="'otherForm' + formIndex" @rightBtnFn="rightBtnFn"></form-common>

        <el-button v-if="!contractInfo.contractStatus" class="f-right padding-top-0 color-red padding-right-20" type="text" @click="deleteOtherItem(formIndex)">删除</el-button>
      </div>
    </template>
    <el-empty v-else description="暂无信息"></el-empty>

    <!-- 验证dialog -->
    <el-dialog title="验证" :visible.sync="verifyDialog" width="60%" :close-on-click-modal="false" :close-on-press-escape="false">
      <form-common v-if="this.currentFiledItem.model.partnerCategory == 1" class="padding-left-10 padding-right-20" :filed-list="groupVerifyList" ref="verifyForm"></form-common>
      <form-common v-if="this.currentFiledItem.model.partnerCategory == 2" class="padding-left-10 padding-right-20" :filed-list="personageVerifyList" ref="verifyForm"></form-common>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="verifyDialog = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmDialog">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  //contractStatus: 0 草稿 1 审批中 2 审批完成/履行中 3 驳回 4 履行完毕 5 已废止
  import formCommon from '@g/components/form/formCommon.vue';
  import { baseInfoFiledList, personageVerifyList, groupVerifyList, otherInfoFiledList, nopaybaseInfoFiledList } from './baseInfo.js';
  import * as Plan from './financePlan.js';
  import { DASE_INFO, PARTNER_LIST } from '@/pages/businessAssets/config';
  import { apiProjectList, apiDepartment, apiLinkContract, apiShopList, apiParkList, apiAdvertList, apiPaysonList, apiAreaList } from '../../../api/contract';
  import { guid, formDataDate } from '@/common/js/utils';
  import bus from '../../../mixin/bus';

  export default {
    props: {
      contractType: {
        type: String,
        default: '',
      },
      //是否是详情
      isInfo: {
        type: String,
        default: '',
      },
      contractInfo: {
        type: Object,
        default: () => {
          return {};
        },
      },
      dictoryList: {
        type: Array,
        default: () => {
          return [];
        },
      },
      //基本信息中选择的项目key
      choseBeginDate: {
        type: Number,
        default: '',
      },
      //基本信息中选择的项目key
      choseEndDate: {
        type: Number,
        default: '',
      },
      isFirst: {
        type: Boolean,
        default: true,
      },
    },

    watch: {
      contractInfo: {
        deep: true,
        handler(obj) {
          let newObj = JSON.parse(JSON.stringify(obj));
          if (this.isInfo && newObj.orgKey && this.isFirst) {
            this.initBaseInfo(newObj);
          }
        },
      },
      dictoryList: {
        immediate: true,
        deep: true,
        handler(obj) {
          this.initSelectOptionList(obj);
        },
      },
      choseBeginDate: {
        deep: true,
        handler(val) {
          console.log(val);
          console.log(12);
          this.currentContractBeginDate = val;
        },
      },
      choseEndDate: {
        deep: true,
        handler(val) {
          this.currentContractEndDate = val;
        },
      },
    },

    data() {
      return {
        dataList: [],
        baseInfoFiledList: [],
        groupVerifyList: groupVerifyList,
        personageVerifyList: personageVerifyList,
        verifyDialog: false,
        otherList: [],
        currentFiledItem: { model: { partnerCategory: '' } }, //表单组件中返回的信息
        statusList: [
          { dictKey: 1, dictValue: '履行中' },
          { dictKey: 2, dictValue: '履行完毕' },
          { dictKey: 3, dictValue: ' 已废止' },
        ],
        userInfo: {},
        constractStatusList: ['草稿', '审批中', '执行中', '驳回', '执行完毕', '已废止'],
        currentProjectKey: '', //基本信息中选择的项目key
        currentContractBeginDate: null, //基本信息中选择的开始时间
        currentContractEndDate: null, //基本信息中选择的结束时间
        Bus: {},
      };
    },

    methods: {
      //基本信息回显
      initBaseInfo(obj) {
        let list = this.getBaseList();
        if (!this.$route.query.isAgreement && obj.contractStatus && obj.contractStatus != 3) {
          this.initFormReadOnly(list);
        }
        this.$refs.form && this.$refs.form.initModel();
        list.forEach(item => {
          for (let i in obj) {
            if (item.bindFieldName == i) {
              item.bindFieldVal = obj[i];
            }
          }
        });
        this.getBaseType();
        this.initOtherList(obj.partnerList);
      },

      //对方信息回显
      initOtherList(list) {
        this.otherList = [];
        list.forEach(item => {
          let otherList = JSON.parse(JSON.stringify(otherInfoFiledList));
          if (!this.$route.query.isAgreement && this.contractInfo.contractStatus && this.contractInfo.contractStatus != 3) {
            this.initFormReadOnly(otherList);
          }
          this.setFiledVal(otherList, item);
          this.otherList.push({
            id: guid(),
            listName: otherList,
          });
        });
      },

      //回显
      setFiledVal(list, row) {
        list.forEach(item => {
          for (let i in row) {
            if (i == item.bindFieldName) {
              item.bindFieldVal = row[i];
            }
          }
        });
      },

      //添加对方信息
      addOtherItem() {
        this.otherList.push({
          id: guid(),
          listName: otherInfoFiledList,
        });
      },

      //删除对方信息
      deleteOtherItem(index) {
        this.otherList.splice(index, 1);
      },

      //dialog 企业或者个人 提交验证
      confirmDialog() {
        let validModel = this.$refs.verifyForm.validateForm();
        if (validModel) {
          this.verifyDialog = false;
        }
      },

      //保存
      saveFn(type) {
        //反出去的表单域的值
        let formAllModle = {};
        //校验基本信息
        formAllModle[DASE_INFO] = this.$refs.form.validateForm();
        if (formAllModle[DASE_INFO]) {
          formAllModle[DASE_INFO].applyUser = this.userInfo.key;
        }

        //校验对方信息
        let validList = [];
        // this.otherList.forEach((con, conIndex) => {
        this.otherList.forEach((vma, vamIndex) => {
          let formName = 'otherForm' + vamIndex; //找到form的ref名字
          let model = type == 'audit' ? this.$refs[formName][0].validateForm() : this.$refs[formName][0].returnModel();
          //更新时需要
          if (this.$route.query.isInfo && model) {
            model.contractKey = this.$route.query.contractKey;
          }
          validList.push(model);
        });

        formAllModle[PARTNER_LIST] = validList.indexOf(false) > -1 ? false : validList;

        if (formAllModle[PARTNER_LIST].length == 0 && type == 'audit') {
          this.$message.warning('请添加对方信息');
          return false;
        }

        let returnModel = JSON.parse(JSON.stringify(formAllModle));
        for (let i in formAllModle) {
          if (formAllModle[i] === false) {
            returnModel = false;
          }
        }
        if (!returnModel) {
          this.$message.warning('请检查必填项!');
        }
        return returnModel;
      },

      //项目信息
      async getProjectList() {
        let res = await apiProjectList();
        let list = this.getBaseList();
        list.forEach(item => {
          if (item.bindFieldName == 'projectKey') {
            item.optionList = res.rows || [];
          }
        });
      },

      //关联合同
      async getLinkContractList() {
        let res = await apiLinkContract();
        let list = this.getBaseList();
        list.forEach(item => {
          if (item.bindFieldName == 'associatedContract') {
            item.optionList = res.rows || [];
          }
        });
      },

      //部门信息
      async getDepartment() {
        let res = await apiDepartment({ employeeKey: this.userInfo.key });
        let list = this.getBaseList();
        list.forEach(item => {
          if (item.bindFieldName == 'orgKey') {
            item.optionList = res.rows || [];
          }
        });
      },

      //初始化下拉框的option
      initSelectOptionList(obj) {
        let list = this.getBaseList();
        list.forEach(item => {
          obj.forEach(dic => {
            if (item.bindFieldName == dic.dictType) {
              item.optionList = dic.dictList;
            }
          });
        });
        //详情时对方信息中的对方名称不展示验证按钮
        if (!obj.contractStatus) {
          otherInfoFiledList.forEach(item => {
            if (item.bindFieldName == 'partnerName') {
              item.isAppendRightBtn = false;
            }
          });
        }
      },

      //组件里的input右键事件
      rightBtnFn(data) {
        this.currentFiledItem = data;
        this.verifyDialog = true;
      },

      //初始化filed只读
      initFormReadOnly(list) {
        list.forEach(item => {
          item.isReadOnly = true;
          item.isRequired = false;
          if (item.type == 'select' || item.type == 'date' || item.type == 'radio' || item.type == 'checkbox') {
            item.isDisabled = true;
          }
        });
      },

      //判断是支出合同还是租赁合同并赋值表单list
      getBaseList() {
        let list = [];
        if (this.contractType == 'ZX' || this.contractType == 'GC' || this.contractType == 'TG' || this.contractType == 'XZ' || this.contractType == 'CW' || this.contractType == 'YY') {
          list = nopaybaseInfoFiledList;
        } else {
          list = baseInfoFiledList;
        }
        return list;
      },

      //区分类型展示不同的基本信息字段
      getBaseType() {
        this.userInfo = JSON.parse(localStorage.getItem('userInfo'));
        if (this.contractType == 'ZX' || this.contractType == 'GC' || this.contractType == 'TG' || this.contractType == 'XZ' || this.contractType == 'CW' || this.contractType == 'YY') {
          this.baseInfoFiledList = nopaybaseInfoFiledList;
        } else {
          this.baseInfoFiledList = baseInfoFiledList;
        }

        this.setFieldBaseVal();

        this.getDepartment();
      },

      //赋值表单一些基础值
      setFieldBaseVal() {
        this.baseInfoFiledList.forEach(item => {
          if (item.bindFieldName == 'applyName' && !this.$route.query.isInfo) {
            item.bindFieldVal = this.userInfo.nickname;
          }
          if (item.bindFieldName == 'contractType') {
            item.bindFieldVal = this.$route.query.contractType;
          }
          if (item.bindFieldName == 'contractName' && this.$route.query.contractType == 'ZL') {
            item.isReadOnly = true;
            item.placeholder = '系统自动填入';
          }
          if (item.bindFieldName == 'statusName') {
            if (!this.contractInfo.contractStatus) {
              item.bindFieldVal = '草稿';
            } else {
              item.bindFieldVal = this.constractStatusList[Number(this.contractInfo.contractStatus)];
            }
          }
        });
      },

      //项目变化的二级联动
      async selectChange(data) {
        if (data.filedName == 'projectKey') {
          this.currentProjectKey = data.filedVal;
          this.$emit('setBaseParams', 'currentProjectKey', data.filedVal);
          this.selectChangeFn();
        }

        // 判断时间
        if (data.filedName == 'contractBeginDate' || data.filedName == 'contractEndDate') {
          let targetFiledName = data.filedName == 'contractBeginDate' ? 'currentContractBeginDate' : 'currentContractEndDate';
          let timestamp = data.model.contractEndDate - data.model.contractBeginDate;
          if (this.$route.query.contractType != 'ZL') {
            this[targetFiledName] = data.filedVal;
          }
          if (timestamp < 0) {
            if (data.filedName == 'contractEndDate') {
              this.$message.warning('合同结束时间应大于合同开始时间');
              data.model.contractEndDate = '';
            }
            if (data.filedName == 'contractBeginDate' && data.model.contractEndDate) {
              this.$message.warning('合同结束时间应大于合同开始时间');
              data.model.contractEndDate = '';
            }
            return;
          }
          if (this.$route.query.contractType != 'ZL') {
            this.$emit('setBaseParams', targetFiledName, data.filedVal);
            this.selectChangeFn();
          }
        }

        //合同类别
        if (data.filedName == 'classification') {
          let classificationName = '';
          data.formItem.optionList.forEach(filed => {
            if (filed.dictKey == data.filedVal) {
              classificationName = filed.dictValue;
            }
          });
          this.$set(this.Bus, 'classificationName', classificationName);
          this.setConstractName();
        }
      },

      //项目变化的二级联动Fn
      async selectChangeFn() {
        let incomeList = ['ZL', 'LSCD', 'WRSB', 'TCCYY', 'QTSR']; //收入类型合同的type值
        if (this.$route.query.contractType == 'ZL') {
          this.getParkList();
          this.getAdvertList();
        }
        if (incomeList.indexOf(this.$route.query.contractType) > -1) {
          this.getChargeItemList('qtsrPayPlanFiledList');
        } else if (this.$route.query.contractType == 'GGZL') {
          this.getChargeItemList('ggwxxGatherFiledList');
        } else {
          this.getChargeItemList('zchtPlanFiledList');
        }
        this.$route.query.contractType == 'GGZL' && this.getAdvertList();
        this.$route.query.contractType == 'TCCYY' && this.getParkList();
        this.$route.query.contractType == 'LSCD' && this.getAreaList();
      },

      //停车场信息
      async getParkList() {
        if (this.currentContractBeginDate && this.currentContractEndDate) {
          let res = await apiParkList({ projectKey: this.currentProjectKey, startDate: this.currentContractBeginDate, endDate: this.currentContractEndDate });
          Plan.tccdyyOtherPlanFiledList.forEach(item => {
            if (item.bindFieldName == 'carParkKey') {
              item.optionList = res.rows || [];
            }
          });
        }
      },

      //广告位信息
      async getAdvertList() {
        if (this.currentContractBeginDate && this.currentContractEndDate) {
          let res = await apiAdvertList({ projectKey: this.currentProjectKey, startDate: this.currentContractBeginDate, endDate: this.currentContractEndDate });
          Plan.ggwxxPlanFiledList.forEach(item => {
            if (item.bindFieldName == 'adKey') {
              item.optionList = res.rows || [];
            }
          });
        }
      },

      //区域信息
      async getAreaList() {
        let res = await apiAreaList({ projectKey: this.currentProjectKey });
        Plan.lscdLeasePlanFiledList.forEach(item => {
          if (item.bindFieldName == 'rentArea') {
            item.optionList = res.rows || [];
          }
        });
      },

      //支出类合同的付费项
      async getChargeItemList(filedName) {
        let res = await apiPaysonList({ contractType: this.contractType });
        Plan[filedName].forEach(item => {
          if (item.bindFieldName == 'chargeItemKey') {
            item.optionList = res.rows || [];
          }
        });
      },

      //设置合同名称 (如果有经营品牌的话，= 经营品牌 + 合同类别；如果有商铺名称的话，= 商铺名称 + 合同类别；否则是当前日期 + 合同类别；)
      setConstractName() {
        let contractName = '';
        if (this.Bus.operateBrandName) {
          contractName = this.Bus.operateBrandName + '-' + this.Bus.classificationName;
        } else if (this.Bus.leaserShopName) {
          contractName = this.Bus.leaserShopName + '-' + this.Bus.classificationName;
        } else {
          contractName = formDataDate(new Date()) + '-' + this.Bus.classificationName;
        }
        this.$refs.form.setFiledSource("contractName",contractName);
      },

      //初始化Bus
      initBus() {
        bus.$on('operateBrandName', data => {
          console.log(this.Bus);
          this.$set(this.Bus, 'operateBrandName', data);
          this.setConstractName();
        });
        bus.$on('leaserShopName', data => {
          console.log(this.Bus);
          this.$set(this.Bus, 'leaserShopName', data);
          this.setConstractName();
        });
      },

      //销毁Bus
      destroyBus() {
        bus.$off('operateBrandName');
        bus.$off('leaserShopName');
      },
    },

    created() {
      this.initBus();
      if (!this.isInfo) {
        this.getBaseType();
      }
      this.getProjectList();
      this.getLinkContractList();
    },

    beforeDestroy() {
      this.destroyBus();
    },

    components: { formCommon },
  };
</script>
<style lang="scss" scoped>
  .el-form {
    margin-left: -10px;
  }
  ::v-deep .el-input.is-disabled .el-input__inner {
    color: #333 !important;
  }
</style>
